package com.cskaoyan.javase.practice.stage8.utils;

import com.cskaoyan.javase.practice.stage8.entity.Student;
import com.cskaoyan.javase.practice.stage8.entity.StudentList;

import java.io.*;

/**
 * @program: little-practice
 * @description: read student list from file and write student list to file
 * @author: Keyu Li
 * @create: 2021-09-20 15:32
 **/

public class FileUtils {

    private FileUtils() {
    }

    // 提取学生信息，从文件中提取student对象，添加到传入的studentlist中，如果读取失败，则返回默认初始化的studentlist
    public static StudentList readStudentList(StudentList stul, String objectFile)
            throws IOException {

        try {
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(objectFile));
            while (true) {
                // 当发生读入异常时候，说明此时文件格式错误，返回运行到此时的 studentlist对象
                Object o;
                if ((o = inputStream.readObject()) == null) break;
                // 如果度过对象时正确的 student 对象，则调用studentlist的add() API 添加从文件中读入的学生。
                if (o instanceof Student)
                    stul.add((Student) o);
            }
            // close
            inputStream.close();
        } catch (Exception e) {
            System.out.println("read exception");
            return stul;
        }

        // 返回修改后的 studentlist对象。
        return stul;
    }


    // 将studentlist对象写入到文件中
    public static Boolean writeStudentList(StudentList stul, String objectFile)
            throws IOException {
        // 对象输出流
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
        // 获取剔除null对象的学生列表
        Student[] students = stul.printList();
        // 将学生列表序列化写入到文件中
        for (int i = 0; i < students.length; i++) {
            try {
                outputStream.writeObject(students[i]);
            } catch (IOException e) {
                System.out.println("write exception!");
                return false;
            }
        }
        // 写入末尾null指示位
        outputStream.writeObject(null);
        // close
        outputStream.close();
        return true;
    }
}
